//Init keys
var input = {
	keys: new Array(),
	keylock: new Array()
}

var mouse = {
	x: 0,
	y: 0,
	press: false
}

function initListeners() {
	window.addEventListener('keydown', keyDown, true);
	window.addEventListener('keyup', keyUp, true);
	window.addEventListener('blur', canvasLostFocus, true);
	initMouseListeners();
}

function canvasLostFocus(evt) {
	input.keys = new Array();
}
function keyDown(evt) {
	input.keys[evt.keyCode] = true;
}
function keyUp(evt) {
	input.keys[evt.keyCode] = false;
	input.keylock[evt.keyCode] = false;
}
function updateArrowKeys() {
	/*
	if (17 in keys && keys[17]) { //ctrl
		alert("CTRL");
		canvasLostFocus();
	}*/
	if (38 in input.keys && input.keys[38] || (87 in input.keys && input.keys[87])) { //up
		if (!game.p.isMoving()) {
			if (isPlaceFree(game.p.getPosX(), game.p.getPosY() - 1)) {
				game.p.moveY(-1);
			}
		}
	}
	if ((39 in input.keys && input.keys[39]) || (68 in input.keys && input.keys[68])) { //right
		if (!game.p.isMoving()) {
			if (isPlaceFree(game.p.getPosX() + 1, game.p.getPosY())) {
				game.p.moveX(1);
			}
		}
	}
	if ((40 in input.keys && input.keys[40]) || (83 in input.keys && input.keys[83])) { //down
		if (!game.p.isMoving()) {
			if (isPlaceFree(game.p.getPosX(), game.p.getPosY() + 1)) {
				game.p.moveY(1);
			}
		}
	}
	if (37 in input.keys && input.keys[37] || (65 in input.keys && input.keys[65])) { //left
		if (!game.p.isMoving()) {
			//alert(isPlaceFree(p.getPosX(), p.getPosY()));
			if (isPlaceFree(game.p.getPosX() - 1, game.p.getPosY())) {
				game.p.moveX(-1);
			}
		}
	}
}


function mouseOutOfCanvas(evt) {
	mouse.press = false;
}
function mouseMove(evt) {
	var c = game.canvas;
    var top = 0;
    var left = 0;
    while (c && c.tagName != 'BODY') {
        top += c.offsetTop;
        left += c.offsetLeft;
        c = c.offsetParent;
    }
    // return relative mouse position
    mouse.x = evt.clientX - left + window.pageXOffset;
    mouse.y = evt.clientY - top + window.pageYOffset;
}
function onClick(evt) {
	
}
function mouseUp(evt) {
	mouse.press = false;
}
function mouseDown(evt) {
	mouse.press = true;
}

function initMouseListeners() {
	window.addEventListener ("mouseout", mouseOutOfCanvas, false);
	window.addEventListener("mousemove", mouseMove, false);
	window.addEventListener("onclick", onClick, false);
	window.addEventListener("mouseup", mouseUp, false);
	window.addEventListener("mousedown", mouseDown, false);
}